import com.totoro.rpc.common.bean.RPCRequest;
import com.totoro.rpc.common.bean.RPCResponse;
import com.totoro.rpc.common.util.StringUtils;
import com.totoro.rpc.register.Discover;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 客户端代理
 * Created by Niki on 2018/5/23 10:51
 */
@Slf4j
public class RPCProxy {
    private Discover discover ;

    public <T> T create(final Class<T> interfaceClass, final String version) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                RPCRequest request = new RPCRequest();
                request.setId(StringUtils.randomUUID());
                request.setServiceName(interfaceClass.getName());
                request.setVersion(version);
                request.setMethodName(method.getName());
                request.setArgs(args);
                request.setClassType(method.getParameterTypes());
                RPCClient client = new RPCClient(discover);
                long time = System.currentTimeMillis();
                RPCResponse response = client.send(request);
                log.info("{}调用时间为：{}", method.getName(), System.currentTimeMillis() - time);
                if (response == null) {
                    throw new RuntimeException("response is null");
                }
                if (response.hasException()) {
                    throw response.getException();
                } else {
                    return response.getResult();
                }
            }
        });
    }

    public static void main(String[] args) {
        System.out.println(Discover.class.getName());
    }
}
